<template>
  <div class="app-container">
    <div
      class="draw-content"
      :style="{ height: `${imageHeight}px`, width: `${imageWidth}px` }"
    >
      <canvas
        id="canvas"
        :width="`${imageWidth}px`"
        :height="`${imageHeight}px`"
        @mousedown="canvasDown"
        @mousemove="canvasMove"
      ></canvas>
      <canvas
        :width="`${imageWidth}px`"
        :height="`${imageHeight}px`"
        id="canvasSave"
      ></canvas>
    </div>
  </div>
</template>

<script>
import { isPointInPolygon, hexToRgba } from '@/utils/canvas'
export default {
  props: ['drawData', 'drawList'],
  emits: ['uploadDraw'],
  data() {
    return {
      imageHeight: 566,
      imageWidth: 800,
      can: null,
      ctx: null,
      canSave: null,
      ctxSave: null,
      pointX: null,
      pointY: null,
      pointArr: [], //存放坐标的数组
      oIndex: -1, //判断鼠标是否移动到起始点处，-1为否，1为是
      canvasWidth: 0,
      canvasHeight: 0,
      currentData: [], // 当前绘制的内容
    }
  },

  mounted() {
    //初始化画布对象
    this.can = document.getElementById('canvas')
    this.ctx = this.can.getContext('2d')
    this.canSave = document.getElementById('canvasSave')
    this.ctxSave = this.canSave.getContext('2d')

    this.ctx.strokeStyle = 'rgba(59, 50, 40,1)' //线条颜色
    this.ctx.lineWidth = 1 //线条粗细
    this.ctxSave.strokeStyle = 'rgba(59, 50, 40,1)' //线条颜色
    this.ctxSave.lineWidth = 1 //线条粗细

    const arr = window.localStorage.getItem('test') ?? ''
    if (arr) {
      this.currentData = JSON.parse(arr)
      this.init()
    }
  },
  methods: {
    //初始化回显
    init() {
      this.currentData.map((item) => {
        this.canvasFill(item.ponitArr, item.color, item.houseName)
      })
    },
    /*点击画点*/
    canvasDown(e) {
      if (e.offsetX || e.layerX) {
        this.pointX = e.offsetX == undefined ? e.layerX : e.offsetX
        this.pointY = e.offsetY == undefined ? e.layerY : e.offsetY
        var piX, piY
        if (this.oIndex > 0 && this.pointArr.length > 0) {
          piX = this.pointArr[0].x
          piY = this.pointArr[0].y
          //画点
          this.makearc(
            this.ctx,
            piX,
            piY,
            this.GetRandomNum(2, 2),
            0,
            180,
            'rgba(102,168,255,1)'
          )
          this.pointArr.push({ x: piX, y: piY })
          this.canvasSave(this.pointArr) //保存点线同步到另一个canvas
          this.saveCanvas() //生成画布
        } else {
          piX = this.pointX
          piY = this.pointY
          this.makearc(
            this.ctx,
            piX,
            piY,
            this.GetRandomNum(2, 2),
            0,
            180,
            'rgba(102,168,255,1)'
          )
          this.pointArr.push({ x: piX, y: piY })
          this.canvasSave(this.pointArr) //保存点线同步到另一个canvas
        }
      }
    },
    // 鼠标移动事件
    canvasMove(e) {
      if (e.offsetX || e.layerX) {
        this.pointX = e.offsetX == undefined ? e.layerX : e.offsetX
        this.pointY = e.offsetY == undefined ? e.layerY : e.offsetY
        var piX, piY
        /*清空画布*/
        this.ctx.clearRect(0, 0, this.can.width, this.can.height)
        /*鼠标下跟随的圆点*/
        this.makearc(
          this.ctx,
          this.pointX,
          this.pointY,
          this.GetRandomNum(4, 4),
          0,
          180,
          'rgba(102,168,255,1)'
        )

        if (this.pointArr.length > 0) {
          if (
            this.pointX > this.pointArr[0].x - 15 &&
            this.pointX < this.pointArr[0].x + 15 &&
            this.pointY > this.pointArr[0].y - 15 &&
            this.pointY < this.pointArr[0].y + 15
          ) {
            if (this.pointArr.length > 1) {
              piX = this.pointArr[0].x
              piY = this.pointArr[0].y
              this.ctx.clearRect(0, 0, this.can.width, this.can.height)
              this.makearc(
                this.ctx,
                piX,
                piY,
                this.GetRandomNum(4, 4),
                0,
                180,
                'rgba(102,168,255,1)'
              )
              this.oIndex = 1
            }
          } else {
            piX = this.pointX
            piY = this.pointY
            this.oIndex = -1
          }
          /*开始绘制*/
          this.ctx.beginPath()
          this.ctx.moveTo(this.pointArr[0].x, this.pointArr[0].y)
          if (this.pointArr.length > 1) {
            for (var i = 1; i < this.pointArr.length; i++) {
              this.ctx.lineTo(this.pointArr[i].x, this.pointArr[i].y)
            }
          }
          this.ctx.lineTo(piX, piY)
          this.ctx.fillStyle = 'rgba(161,195,255,1)' //填充颜色
          this.ctx.fill() //填充
          this.ctx.stroke() //绘制
        }
      }
    },
    // 存储已生成的点线
    canvasSave(pointArr) {
      this.ctxSave.clearRect(0, 0, this.ctxSave.width, this.ctxSave.height)
      this.ctxSave.beginPath()
      if (pointArr.length > 1) {
        this.ctxSave.moveTo(pointArr[0].x, pointArr[0].y)
        for (var i = 1; i < pointArr.length; i++) {
          this.ctxSave.lineTo(pointArr[i].x, pointArr[i].y)
          this.ctxSave.fillStyle = 'rgba(161,195,255,0.2)' //填充颜色
          // this.ctxSave.fill();
          this.ctxSave.stroke() //绘制
        }
        this.ctxSave.closePath()
      }
      //判断最后一个点重合则结束绘制
      if (pointArr.length > 1) {
        let { 0: a, [pointArr.length - 1]: b } = pointArr
        if (a.x == b.x && b.y == b.y) {
          const current = [
            {
              color: '#ff0000',
              houseName: '绘制区域',
              ponitArr: pointArr,
            },
          ]
          const arr = [...this.currentData, ...current]
          window.localStorage.setItem('test', JSON.stringify(arr))
        }
      }
    },
    //回显canvas区域
    canvasFill(pointArr, color, houseName) {
      this.ctxSave.clearRect(0, 0, this.ctxSave.width, this.ctxSave.height)
      this.ctxSave.beginPath()
      if (pointArr.length > 1) {
        this.ctxSave.moveTo(pointArr[0].x, pointArr[0].y)
        for (var i = 1; i < pointArr.length; i++) {
          this.ctxSave.lineTo(pointArr[i].x, pointArr[i].y)
        }
        this.ctxSave.fillStyle = hexToRgba(color, 0.5) //填充颜色     ${color}6B   ${color}
        this.ctxSave.fill()
        this.ctxSave.stroke() //绘制

        const dimensions = this.getPolygonDimensions(pointArr)
        this.canvasText(
          houseName,
          { x: dimensions.minX, y: dimensions.minY },
          dimensions
        )
      }
    },
    //绘制文字
    canvasText(text, point, dimensions) {
      this.ctxSave.textAlign = 'center' //设置文本对齐方式
      this.ctxSave.textBaseline = 'middle' //文本基线

      this.ctxSave.fillStyle = '#000' //字体颜色
      this.ctxSave.font = 'italic bold 10px Arial' // 设置字体样式、粗细和大小
      const x = point.x + dimensions.width / 2
      const y = point.y + dimensions.height / 2
      this.ctxSave.fillText(text, x, y) //绘制文字
    },
    /*生成画布 结束绘画*/
    saveCanvas() {
      this.ctx.clearRect(0, 0, this.can.width, this.can.height)
      this.ctxSave.closePath() //结束路径状态，结束当前路径，如果是一个未封闭的图形，会自动将首尾相连封闭起来
      this.ctxSave.fill() //填充
      this.ctxSave.stroke() //绘制
      this.pointArr = []
    },
    /*canvas生成圆点*/
    GetRandomNum(Min, Max) {
      var Range = Max - Min
      var Rand = Math.random()
      return Min + Math.round(Rand * Range)
    },
    makearc(ctx, x, y, r, s, e, color) {
      ctx.clearRect(0, 0, 199, 202) //清空画布
      ctx.beginPath()
      ctx.fillStyle = color
      ctx.arc(x, y, r, s, e)
      ctx.fill()
    },
    // 获取多边形的宽高
    getPolygonDimensions(points) {
      let minX = points[0].x
      let maxX = points[0].x
      let minY = points[0].y
      let maxY = points[0].y
      // 找到多边形的最左、最右、最上和最下的顶点
      for (let i = 1; i < points.length; i++) {
        minX = Math.min(minX, points[i].x)
        maxX = Math.max(maxX, points[i].x)
        minY = Math.min(minY, points[i].y)
        maxY = Math.max(maxY, points[i].y)
      }

      // 计算多边形的宽度和高度
      const width = maxX - minX
      const height = maxY - minY
      return { width, height, minX, minY }
    },
  },
}
</script>

<style scoped>
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.draw-content {
  position: relative;
}
canvas {
  position: relative;
  border: 1px solid #333;
  display: block;
}

#canvas {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
  cursor: crosshair;
}

#canvasSave {
  position: absolute;
  left: 0;
  top: 0;
  background-repeat: 'no-repeat';
  background-position: 'top center';
  background: url('@/assets/table.jpg');
}
</style>
